#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2016年2月29日

@author: yangzhou1
'''
from lib.correlation import *
from sklearn.metrics import ranking

def top_matches(matrix,item,n=5,similarity=tanimoto_distance):
    scores=[(similarity(matrix,item,other),other) for other in matrix if other != item ]
    scores.sort(cmp=None, key=None, reverse=True)
    return scores[0:n]
'''
推荐列表
将同每个人的相似度 * 每部未看电影的评分
基于用户的协作型过滤
'''
def getRecommendadPeoples(matrix,item,similarity=tanimoto_distance):
    totalScores={}
    sumSimilarity={}
    for other in matrix:
        if other !=item :#排除自己
            sim=similarity(matrix,item,other)
        if sum>0:
            for movie in matrix[other]:
                if movie not in matrix[item] or matrix[item][movie]==0: #只推荐未看的
                    totalScores.setdefault(movie,0)
                    totalScores[movie]+=matrix[other][movie] * sim
                    
                    sumSimilarity.setdefault(movie,0)
                    sumSimilarity[movie]+=sim
    #返回电影推荐的序列，每部电影的评分为 每项电影的加权总分除以总相似度
    rankings=[(total/sumSimilarity[movie],movie) for movie,total in totalScores.items()]
    rankings.sort(cmp=None, key=None, reverse=True)
    return rankings
def getRecommendedItems(matrix,itemMatch,people):
    peopleRatings=matrix[people]
    scores={}
    totalSim={}
    #当前用户的评分
    for (item,rating) in peopleRatings.items():
        #与当前物品相近的物品
        for (similarity,item2) in itemMatch[item]:
            if item2 in peopleRatings:
                continue
            #评价的加权值之和
            scores.setdefault(item2,0)
            scores[item2]+=similarity*rating
            #相似度之和
            totalSim.setdefault(item2,0)
            totalSim[item2]+=similarity
    #每个物品的加权值 除以 相似度之和
    rankings=[(score/totalSim[item],item) for item,score in scores.items()]
    rankings.sort(cmp=None, key=None, reverse=True)
    return rankings
'''
基于物品的协作型过滤
'''
def calculateSimilarItems(matrix,n=10):
    result={}
    
    itemMatrix=transformMatrix(matrix)
    
    c=0
    for i in itemMatrix:
        c+=1
        #进度报告
        if c%100==0:
            print ("%d / %d" (c,len(itemMatrix)))
        scores=top_matches(itemMatrix, i, n=n, similarity=tanimoto_distance)   
        result[i]=scores
    return result
'''
矩阵转置
'''
def transformMatrix(matrix):
    result={}
    for item1 in matrix:
        for item2 in matrix[item1]:
            result.setdefault(item2,{})
            result[item2][item1]=matrix[item1][item2]
            
    return result
if __name__ == '__main__':
    print (getRecommendadPeoples(critics,"Toby"))
    print (getRecommendedItems(critics,calculateSimilarItems(critics),"Toby"))
    pass